package com.generalbackend.common.util;

import com.generalbackend.common.exception.EToolsRuntimeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author tim.xie
 * @date 2021/11/19 15:07
 */
@Slf4j
public class ResponseUtil {

    public static void responseFile(HttpServletResponse response, String filePath) {
        CheckFileUtil.checkDownloadFile(filePath);
        responseFile(response, new File(filePath));
    }

    /**
     * 响应文件
     * @param response
     * @param file
     */
    public static void responseFile(HttpServletResponse response, File file) {
        if (!file.exists()) {
            throw new EToolsRuntimeException(String.format("%s 文件不存在", file.getAbsolutePath()));
        }
        ServletOutputStream out = null;
        FileInputStream in = null;
        try {
            String contentType = "application/force-download";
            response.setContentType(contentType);
            // 设置自动下载功能
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename="+ URLEncoder.encode(file.getName(),"UTF-8"));
            in = new FileInputStream(file);
            out = response.getOutputStream();
            // 读取文件流
            int len = 0;
            byte[] buffer = new byte[1024*10];
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
            log.info("{}文件下载成功", file.getName());
        } catch (Exception e) {
            log.error("文件下载失败", e);
        } finally {
            try {
                if(out != null) {
                    out.close();
                }
                if(in !=null) {
                    in.close();
                }
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
